package com.yc.sell.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yc.sell.VO.ProductInfoVO;
import com.yc.sell.VO.ProductVO;
import com.yc.sell.VO.ResultVO;
import com.yc.sell.domain.ProductCategory;
import com.yc.sell.domain.ProductInfo;
import com.yc.sell.service.CategoryService;
import com.yc.sell.service.ProductService;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ProductService productService;

	@RequestMapping("/list")
	public ResultVO<List<ProductVO>> list() {

		// 1. 查询所有的上架商品
		List<ProductInfo> productInfoList = productService.findUpAll();

		// 2. 查询类目(一次性查询)
		List<Integer> categoryTypeList = new ArrayList<>();
		for (ProductInfo productInfo : productInfoList) {
			categoryTypeList.add(productInfo.getCategoryType());
		}
		List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
		// 3.拼装数据
		List<ProductVO> productVOList = new ArrayList<>();
		for (ProductCategory productCategory : productCategoryList) {

			ProductVO productVO = new ProductVO();
			productVO.setProductName(productCategory.getCategoryName());
			productVO.setProductType(productCategory.getCategoryType());

			List<ProductInfoVO> productInfoVOList = new ArrayList<>();

			for (ProductInfo productInfo : productInfoList) {
				if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
					ProductInfoVO productInfoVO = new ProductInfoVO();
					BeanUtils.copyProperties(productInfo, productInfoVO);
					productInfoVOList.add(productInfoVO);
				}
			}
			productVO.setProductInfoVOList(productInfoVOList);
			productVOList.add(productVO);
		}
		ResultVO<List<ProductVO>> resultVO = new ResultVO<>();
		resultVO.setCode(0);
		resultVO.setMsg("成功");
		resultVO.setData(productVOList);
		return resultVO;
	}
}
